package com.su.kddq.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.su.kddq.constant.OrderStateConstant;
import com.su.kddq.constant.RabbitMqConstant;
import com.su.kddq.constant.TxStateConstant;
import com.su.kddq.entity.courier.CourierOrder;
import com.su.kddq.entity.user.CourierStatus;
import com.su.kddq.entity.user.PayOrder;
import com.su.kddq.entity.user.User;
import com.su.kddq.entity.user.UserWallet;
import com.su.kddq.mapper.courier.CourierOrderMapper;
import com.su.kddq.mapper.courier.CourierStatusMapper;
import com.su.kddq.mapper.user.PayOrderMapper;
import com.su.kddq.mapper.user.UserMapper;
import com.su.kddq.mapper.user.UserWalletMapper;
import com.su.kddq.utils.GeTuiUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;


/**
 * MQ消费
 *
 * @author sx
 */
@Slf4j
@Component
public class OrderListener {

    @Autowired
    private UserWalletMapper userWalletMapper;

    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private GeTuiUtils geTuiUtils;

    @Autowired
    private CourierOrderMapper courierOrderMapper;

    @Autowired
    private CourierStatusMapper courierStatusMapper;

    /**
     * 监听充值队列。消费消息
     *
     * @param message
     * @throws IOException
     */
    @RabbitListener(queues = RabbitMqConstant.QUEUE_ORDER)
    @Transactional(rollbackFor = Exception.class)
    public void CreateCourierOrder(Message message) throws Exception {
        byte[] body = message.getBody();
        Map map = JSON.parseObject(body, Map.class);
        String trade_no = (String) map.get("trade_no");
        PayOrder payOrder = payOrderMapper.selectOne(new QueryWrapper<PayOrder>().eq("pay_order_id", map.get("payOrderId")));
        payOrder.setStatus(OrderStateConstant.RECHARGE_ORDER_STATE_YES);
        payOrder.setTradeNo(trade_no);
        //将用户支付充值订单状态修改为1（已支付）
        payOrderMapper.updateById(payOrder);
        //创建用户充值订单记录
        UserWallet userWallet = userWalletMapper.selectOne(new QueryWrapper<UserWallet>().eq("uid", payOrder.getUid()));
        if (StringUtils.isEmpty(userWallet)) {
            //第一次充值，新增钱包记录
            UserWallet wallet = new UserWallet();
            wallet.setBalance(payOrder.getMoney());
            wallet.setCreatTime(new Date());
            wallet.setUpdateTime(new Date());
            wallet.setWalletId(UUID.randomUUID().toString().replace("-", ""));
            wallet.setUid(Integer.valueOf(payOrder.getUid()));
            userWalletMapper.insert(wallet);
        } else {
            //更新钱包余额
            userWallet.setBalance(userWallet.getBalance() + payOrder.getMoney());
            userWalletMapper.updateById(userWallet);
        }
    }

    /**
     * 监听cid推送队列
     *
     * @param message
     * @throws Exception
     */
    @RabbitListener(queues = RabbitMqConstant.QUEUE_MSG)
    public void SendMsWithCid(Message message) throws Exception {
        byte[] body = message.getBody();
        Map map = JSON.parseObject(body, Map.class);
        //向指定的cid用户推送消息
        User user = userMapper.selectOne(new QueryWrapper<User>().select("cid").eq("id", map.get("uid")));
        Object orderState = map.get("orderState");
        String content;
        if (orderState.equals(OrderStateConstant.ORDER_DQJ)) {
            content = "您的订单已分配到取件员,正在取件,单号：" + map.get("orderId");
        } else if (orderState.equals(OrderStateConstant.ORDER_PSZ)) {
            content = "您的订单正在派送中,单号" + map.get("orderId");
        } else {
            content = "您的订单已送到,感谢您使用高校行者！单号：" + map.get("orderId");
        }
        geTuiUtils.pushToSingleByCid(user.getCid(), "订单状态更新", content);
    }


    /**
     * 监听取件员提现队列
     *
     * @param message
     * @throws Exception
     */
    @RabbitListener(queues = RabbitMqConstant.QUEUE_TX)
    public void Tx(Message message) throws Exception {
        byte[] body = message.getBody();
        Map map = JSON.parseObject(body, Map.class);
        List<String> orderIds = (List<String>) map.get("orderIds");
        Object cid = map.get("cid");
        Object txId = map.get("txId");
        List<CourierOrder> courierOrders = courierOrderMapper.selectList(new QueryWrapper<CourierOrder>().select("is_tx")
                .in("id", orderIds));
        List<Integer> isTxs = courierOrders.stream().map(CourierOrder::getIsTx).collect(Collectors.toList());
        if (isTxs.contains(OrderStateConstant.ORDER_TX_YES)){
            courierStatusMapper.update(null,new UpdateWrapper<CourierStatus>().set("tx_state",TxStateConstant.TX_STATE_FAIL).eq("uid", cid));
            log.error("风险提现");
            return;
        }
        //更新订单已提现状态并关联tx_id
        courierOrderMapper.update(null, new UpdateWrapper<CourierOrder>().set("is_tx", OrderStateConstant.ORDER_TX_YES)
                .set("tx_id",txId)
                .in("id", orderIds).eq("cid", cid));
    }
}
